<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Middleware &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Handling HTTP requests" href="index.html" />
    <link rel="next" title="How to use sessions" href="sessions.html" />
    <link rel="prev" title="Generic views" href="generic-views.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="generic-views.html" title="Generic views">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="sessions.html" title="How to use sessions">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-http-middleware">
            
  <div class="section" id="s-middleware">
<span id="middleware"></span><h1>Middleware<a class="headerlink" href="#middleware" title="Permalink to this headline">¶</a></h1>
<p>Middleware is a framework of hooks into Django&#8217;s request/response processing.
It&#8217;s a light, low-level &#8220;plugin&#8221; system for globally altering Django&#8217;s input
or output.</p>
<p>Each middleware component is responsible for doing some specific function. For
example, Django includes a middleware component,
<a class="reference internal" href="../../ref/middleware.html#django.middleware.transaction.TransactionMiddleware" title="django.middleware.transaction.TransactionMiddleware"><tt class="xref py py-class docutils literal"><span class="pre">TransactionMiddleware</span></tt></a>, that wraps the
processing of each HTTP request in a database transaction.</p>
<p>This document explains how middleware works, how you activate middleware, and
how to write your own middleware. Django ships with some built-in middleware
you can use right out of the box. They&#8217;re documented in the <a class="reference internal" href="../../ref/middleware.html"><em>built-in
middleware reference</em></a>.</p>
<div class="section" id="s-activating-middleware">
<span id="activating-middleware"></span><h2>Activating middleware<a class="headerlink" href="#activating-middleware" title="Permalink to this headline">¶</a></h2>
<p>To activate a middleware component, add it to the
<a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> tuple in your Django settings.</p>
<p>In <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a>, each middleware component is represented by
a string: the full Python path to the middleware&#8217;s class name. For example,
here&#8217;s the default value created by <a class="reference internal" href="../../ref/django-admin.html#django-admin-startproject"><tt class="xref std std-djadmin docutils literal"><span class="pre">django-admin.py</span> <span class="pre">startproject</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">MIDDLEWARE_CLASSES</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s">&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.middleware.common.CommonMiddleware&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.middleware.csrf.CsrfViewMiddleware&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.messages.middleware.MessageMiddleware&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>A Django installation doesn&#8217;t require any middleware —
<a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> can be empty, if you&#8217;d like — but it&#8217;s strongly
suggested that you at least use
<a class="reference internal" href="../../ref/middleware.html#django.middleware.common.CommonMiddleware" title="django.middleware.common.CommonMiddleware"><tt class="xref py py-class docutils literal"><span class="pre">CommonMiddleware</span></tt></a>.</p>
<p>The order in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> matters because a middleware can
depend on other middleware. For instance,
<a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><tt class="xref py py-class docutils literal"><span class="pre">AuthenticationMiddleware</span></tt></a> stores the
authenticated user in the session; therefore, it must run after
<a class="reference internal" href="../../ref/middleware.html#django.contrib.sessions.middleware.SessionMiddleware" title="django.contrib.sessions.middleware.SessionMiddleware"><tt class="xref py py-class docutils literal"><span class="pre">SessionMiddleware</span></tt></a>. See
<a class="reference internal" href="../../ref/middleware.html#middleware-ordering"><em>Middleware ordering</em></a> for some common hints about ordering of Django
middleware classes.</p>
</div>
<div class="section" id="s-hooks-and-application-order">
<span id="hooks-and-application-order"></span><h2>Hooks and application order<a class="headerlink" href="#hooks-and-application-order" title="Permalink to this headline">¶</a></h2>
<p>During the request phase, before calling the view, Django applies middleware
in the order it&#8217;s defined in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a>, top-down. Two
hooks are available:</p>
<ul class="simple">
<li><a class="reference internal" href="#process_request" title="process_request"><tt class="xref py py-meth docutils literal"><span class="pre">process_request()</span></tt></a></li>
<li><a class="reference internal" href="#process_view" title="process_view"><tt class="xref py py-meth docutils literal"><span class="pre">process_view()</span></tt></a></li>
</ul>
<p>During the response phase, after calling the view, middleware are applied in
reverse order, from the bottom up. Three hooks are available:</p>
<ul class="simple">
<li><a class="reference internal" href="#process_exception" title="process_exception"><tt class="xref py py-meth docutils literal"><span class="pre">process_exception()</span></tt></a> (only if the view raised an exception)</li>
<li><a class="reference internal" href="#process_template_response" title="process_template_response"><tt class="xref py py-meth docutils literal"><span class="pre">process_template_response()</span></tt></a> (only for template responses)</li>
<li><a class="reference internal" href="#process_response" title="process_response"><tt class="xref py py-meth docutils literal"><span class="pre">process_response()</span></tt></a></li>
</ul>
<a class="reference internal image-reference" href="../../_images/middleware.svg"><img alt="middleware application order" height="409" src="../../_images/middleware.svg" width="481" /></a>
<p>If you prefer, you can also think of it like an onion: each middleware class
is a &#8220;layer&#8221; that wraps the view.</p>
<p>The behavior of each hook is described below.</p>
</div>
<div class="section" id="s-writing-your-own-middleware">
<span id="writing-your-own-middleware"></span><h2>Writing your own middleware<a class="headerlink" href="#writing-your-own-middleware" title="Permalink to this headline">¶</a></h2>
<p>Writing your own middleware is easy. Each middleware component is a single
Python class that defines one or more of the following methods:</p>
<div class="section" id="s-process-request">
<span id="s-request-middleware"></span><span id="process-request"></span><span id="request-middleware"></span><h3><tt class="docutils literal"><span class="pre">process_request</span></tt><a class="headerlink" href="#process-request" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="process_request">
<tt class="descname">process_request</tt>(<em>request</em>)<a class="headerlink" href="#process_request" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p><tt class="docutils literal"><span class="pre">request</span></tt> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> object.</p>
<p><tt class="docutils literal"><span class="pre">process_request()</span></tt> is called on each request, before Django decides which
view to execute.</p>
<p>It should return either <tt class="docutils literal"><span class="pre">None</span></tt> or an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>
object. If it returns <tt class="docutils literal"><span class="pre">None</span></tt>, Django will continue processing this request,
executing any other <tt class="docutils literal"><span class="pre">process_request()</span></tt> middleware, then, <tt class="docutils literal"><span class="pre">process_view()</span></tt>
middleware, and finally, the appropriate view. If it returns an
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> object, Django won&#8217;t bother calling any
other request, view or exception middleware, or the appropriate view; it&#8217;ll
apply response middleware to that <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>, and
return the result.</p>
</div>
<div class="section" id="s-process-view">
<span id="s-view-middleware"></span><span id="process-view"></span><span id="view-middleware"></span><h3><tt class="docutils literal"><span class="pre">process_view</span></tt><a class="headerlink" href="#process-view" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="process_view">
<tt class="descname">process_view</tt>(<em>request</em>, <em>view_func</em>, <em>view_args</em>, <em>view_kwargs</em>)<a class="headerlink" href="#process_view" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p><tt class="docutils literal"><span class="pre">request</span></tt> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> object. <tt class="docutils literal"><span class="pre">view_func</span></tt> is
the Python function that Django is about to use. (It&#8217;s the actual function
object, not the name of the function as a string.) <tt class="docutils literal"><span class="pre">view_args</span></tt> is a list of
positional arguments that will be passed to the view, and <tt class="docutils literal"><span class="pre">view_kwargs</span></tt> is a
dictionary of keyword arguments that will be passed to the view. Neither
<tt class="docutils literal"><span class="pre">view_args</span></tt> nor <tt class="docutils literal"><span class="pre">view_kwargs</span></tt> include the first view argument
(<tt class="docutils literal"><span class="pre">request</span></tt>).</p>
<p><tt class="docutils literal"><span class="pre">process_view()</span></tt> is called just before Django calls the view.</p>
<p>It should return either <tt class="docutils literal"><span class="pre">None</span></tt> or an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>
object. If it returns <tt class="docutils literal"><span class="pre">None</span></tt>, Django will continue processing this request,
executing any other <tt class="docutils literal"><span class="pre">process_view()</span></tt> middleware and, then, the appropriate
view. If it returns an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> object, Django won&#8217;t
bother calling any other view or exception middleware, or the appropriate
view; it&#8217;ll apply response middleware to that
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>, and return the result.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Accessing <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.POST" title="django.http.HttpRequest.POST"><tt class="xref py py-attr docutils literal"><span class="pre">request.POST</span></tt></a> or
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.REQUEST" title="django.http.HttpRequest.REQUEST"><tt class="xref py py-attr docutils literal"><span class="pre">request.REQUEST</span></tt></a> inside middleware
from <tt class="docutils literal"><span class="pre">process_request</span></tt> or <tt class="docutils literal"><span class="pre">process_view</span></tt> will prevent any view running
after the middleware from being able to <a class="reference internal" href="file-uploads.html#modifying-upload-handlers-on-the-fly"><em>modify the upload handlers
for the request</em></a>, and should
normally be avoided.</p>
<p class="last">The <a class="reference internal" href="../../ref/middleware.html#django.middleware.csrf.CsrfViewMiddleware" title="django.middleware.csrf.CsrfViewMiddleware"><tt class="xref py py-class docutils literal"><span class="pre">CsrfViewMiddleware</span></tt></a> class can be
considered an exception, as it provides the
<a class="reference internal" href="../../ref/contrib/csrf.html#django.views.decorators.csrf.csrf_exempt" title="django.views.decorators.csrf.csrf_exempt"><tt class="xref py py-func docutils literal"><span class="pre">csrf_exempt()</span></tt></a> and
<a class="reference internal" href="../../ref/contrib/csrf.html#django.views.decorators.csrf.csrf_protect" title="django.views.decorators.csrf.csrf_protect"><tt class="xref py py-func docutils literal"><span class="pre">csrf_protect()</span></tt></a> decorators which allow
views to explicitly control at what point the CSRF validation should occur.</p>
</div>
</div>
<div class="section" id="s-process-template-response">
<span id="s-template-response-middleware"></span><span id="process-template-response"></span><span id="template-response-middleware"></span><h3><tt class="docutils literal"><span class="pre">process_template_response</span></tt><a class="headerlink" href="#process-template-response" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="process_template_response">
<tt class="descname">process_template_response</tt>(<em>request</em>, <em>response</em>)<a class="headerlink" href="#process_template_response" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p><tt class="docutils literal"><span class="pre">request</span></tt> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> object. <tt class="docutils literal"><span class="pre">response</span></tt> is
the <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><tt class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></tt></a> object (or equivalent)
returned by a Django view or by a middleware.</p>
<p><tt class="docutils literal"><span class="pre">process_template_response()</span></tt> is called just after the view has finished
executing, if the response instance has a <tt class="docutils literal"><span class="pre">render()</span></tt> method, indicating that
it is a <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><tt class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></tt></a> or equivalent.</p>
<p>It must return a response object that implements a <tt class="docutils literal"><span class="pre">render</span></tt> method. It could
alter the given <tt class="docutils literal"><span class="pre">response</span></tt> by changing <tt class="docutils literal"><span class="pre">response.template_name</span></tt> and
<tt class="docutils literal"><span class="pre">response.context_data</span></tt>, or it could create and return a brand-new
<a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><tt class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></tt></a> or equivalent.</p>
<p>You don&#8217;t need to explicitly render responses &#8211; responses will be
automatically rendered once all template response middleware has been
called.</p>
<p>Middleware are run in reverse order during the response phase, which
includes <tt class="docutils literal"><span class="pre">process_template_response()</span></tt>.</p>
</div>
<div class="section" id="s-process-response">
<span id="s-response-middleware"></span><span id="process-response"></span><span id="response-middleware"></span><h3><tt class="docutils literal"><span class="pre">process_response</span></tt><a class="headerlink" href="#process-response" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="process_response">
<tt class="descname">process_response</tt>(<em>request</em>, <em>response</em>)<a class="headerlink" href="#process_response" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p><tt class="docutils literal"><span class="pre">request</span></tt> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> object. <tt class="docutils literal"><span class="pre">response</span></tt> is
the <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> or
<a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></tt></a> object returned by a Django view
or by a middleware.</p>
<p><tt class="docutils literal"><span class="pre">process_response()</span></tt> is called on all responses before they&#8217;re returned to
the browser.</p>
<p>It must return an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> or
<a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></tt></a> object. It could alter the given
<tt class="docutils literal"><span class="pre">response</span></tt>, or it could create and return a brand-new
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> or
<a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></tt></a>.</p>
<p>Unlike the <tt class="docutils literal"><span class="pre">process_request()</span></tt> and <tt class="docutils literal"><span class="pre">process_view()</span></tt> methods, the
<tt class="docutils literal"><span class="pre">process_response()</span></tt> method is always called, even if the
<tt class="docutils literal"><span class="pre">process_request()</span></tt> and <tt class="docutils literal"><span class="pre">process_view()</span></tt> methods of the same middleware
class were skipped (because an earlier middleware method returned an
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>). In particular, this means that your
<tt class="docutils literal"><span class="pre">process_response()</span></tt> method cannot rely on setup done in
<tt class="docutils literal"><span class="pre">process_request()</span></tt>.</p>
<p>Finally, remember that during the response phase, middleware are applied in
reverse order, from the bottom up. This means classes defined at the end of
<a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> will be run first.</p>
<div class="section" id="s-dealing-with-streaming-responses">
<span id="dealing-with-streaming-responses"></span><h4>Dealing with streaming responses<a class="headerlink" href="#dealing-with-streaming-responses" title="Permalink to this headline">¶</a></h4>
<p>Unlike <a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>,
<a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></tt></a> does not have a <tt class="docutils literal"><span class="pre">content</span></tt>
attribute. As a result, middleware can no longer assume that all responses
will have a <tt class="docutils literal"><span class="pre">content</span></tt> attribute. If they need access to the content, they
must test for streaming responses and adjust their behavior accordingly:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">response</span><span class="o">.</span><span class="n">streaming</span><span class="p">:</span>
    <span class="n">response</span><span class="o">.</span><span class="n">streaming_content</span> <span class="o">=</span> <span class="n">wrap_streaming_content</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">streaming_content</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">response</span><span class="o">.</span><span class="n">content</span> <span class="o">=</span> <span class="n">alter_content</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p><tt class="docutils literal"><span class="pre">streaming_content</span></tt> should be assumed to be too large to hold in memory.
Response middleware may wrap it in a new generator, but must not consume
it. Wrapping is typically implemented as follows:</p>
<div class="last highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">wrap_streaming_content</span><span class="p">(</span><span class="n">content</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">content</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">alter_content</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="s-process-exception">
<span id="s-exception-middleware"></span><span id="process-exception"></span><span id="exception-middleware"></span><h3><tt class="docutils literal"><span class="pre">process_exception</span></tt><a class="headerlink" href="#process-exception" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="process_exception">
<tt class="descname">process_exception</tt>(<em>request</em>, <em>exception</em>)<a class="headerlink" href="#process_exception" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p><tt class="docutils literal"><span class="pre">request</span></tt> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> object. <tt class="docutils literal"><span class="pre">exception</span></tt> is an
<tt class="docutils literal"><span class="pre">Exception</span></tt> object raised by the view function.</p>
<p>Django calls <tt class="docutils literal"><span class="pre">process_exception()</span></tt> when a view raises an exception.
<tt class="docutils literal"><span class="pre">process_exception()</span></tt> should return either <tt class="docutils literal"><span class="pre">None</span></tt> or an
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> object. If it returns an
<a class="reference internal" href="../../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a> object, the template response and response
middleware will be applied, and the resulting response returned to the
browser. Otherwise, default exception handling kicks in.</p>
<p>Again, middleware are run in reverse order during the response phase, which
includes <tt class="docutils literal"><span class="pre">process_exception</span></tt>. If an exception middleware returns a response,
the middleware classes above that middleware will not be called at all.</p>
</div>
<div class="section" id="s-init">
<span id="init"></span><h3><tt class="docutils literal"><span class="pre">__init__</span></tt><a class="headerlink" href="#init" title="Permalink to this headline">¶</a></h3>
<p>Most middleware classes won&#8217;t need an initializer since middleware classes are
essentially placeholders for the <tt class="docutils literal"><span class="pre">process_*</span></tt> methods. If you do need some
global state you may use <tt class="docutils literal"><span class="pre">__init__</span></tt> to set up. However, keep in mind a couple
of caveats:</p>
<ul class="simple">
<li>Django initializes your middleware without any arguments, so you can&#8217;t
define <tt class="docutils literal"><span class="pre">__init__</span></tt> as requiring any arguments.</li>
<li>Unlike the <tt class="docutils literal"><span class="pre">process_*</span></tt> methods which get called once per request,
<tt class="docutils literal"><span class="pre">__init__</span></tt> gets called only <em>once</em>, when the Web server responds to the
first request.</li>
</ul>
<div class="section" id="s-marking-middleware-as-unused">
<span id="marking-middleware-as-unused"></span><h4>Marking middleware as unused<a class="headerlink" href="#marking-middleware-as-unused" title="Permalink to this headline">¶</a></h4>
<p>It&#8217;s sometimes useful to determine at run-time whether a piece of middleware
should be used. In these cases, your middleware&#8217;s <tt class="docutils literal"><span class="pre">__init__</span></tt> method may
raise <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.MiddlewareNotUsed" title="django.core.exceptions.MiddlewareNotUsed"><tt class="xref py py-exc docutils literal"><span class="pre">django.core.exceptions.MiddlewareNotUsed</span></tt></a>. Django will then remove
that piece of middleware from the middleware process.</p>
</div>
</div>
<div class="section" id="s-guidelines">
<span id="guidelines"></span><h3>Guidelines<a class="headerlink" href="#guidelines" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>Middleware classes don&#8217;t have to subclass anything.</li>
<li>The middleware class can live anywhere on your Python path. All Django
cares about is that the <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><tt class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a> setting includes
the path to it.</li>
<li>Feel free to look at <a class="reference internal" href="../../ref/middleware.html"><em>Django&#8217;s available middleware</em></a> for examples.</li>
<li>If you write a middleware component that you think would be useful to
other people, contribute to the community! <a class="reference internal" href="../../internals/contributing/index.html"><em>Let us know</em></a>, and we&#8217;ll consider adding it to Django.</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Middleware</a><ul>
<li><a class="reference internal" href="#activating-middleware">Activating middleware</a></li>
<li><a class="reference internal" href="#hooks-and-application-order">Hooks and application order</a></li>
<li><a class="reference internal" href="#writing-your-own-middleware">Writing your own middleware</a><ul>
<li><a class="reference internal" href="#process-request"><tt class="docutils literal"><span class="pre">process_request</span></tt></a></li>
<li><a class="reference internal" href="#process-view"><tt class="docutils literal"><span class="pre">process_view</span></tt></a></li>
<li><a class="reference internal" href="#process-template-response"><tt class="docutils literal"><span class="pre">process_template_response</span></tt></a></li>
<li><a class="reference internal" href="#process-response"><tt class="docutils literal"><span class="pre">process_response</span></tt></a><ul>
<li><a class="reference internal" href="#dealing-with-streaming-responses">Dealing with streaming responses</a></li>
</ul>
</li>
<li><a class="reference internal" href="#process-exception"><tt class="docutils literal"><span class="pre">process_exception</span></tt></a></li>
<li><a class="reference internal" href="#init"><tt class="docutils literal"><span class="pre">__init__</span></tt></a><ul>
<li><a class="reference internal" href="#marking-middleware-as-unused">Marking middleware as unused</a></li>
</ul>
</li>
<li><a class="reference internal" href="#guidelines">Guidelines</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="generic-views.html">Generic views</a></li>
    
    
      <li>Next: <a href="sessions.html">How to use sessions</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Handling HTTP requests</a>
        
        <ul><li>Middleware</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/http/middleware.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="generic-views.html" title="Generic views">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="sessions.html" title="How to use sessions">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>